package com.gshrms.framework.aspectj;

import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gshrms.common.core.domain.CommonEntity;
import com.gshrms.common.core.domain.entity.SysMenu;
import com.gshrms.common.core.page.PageDomain;
import com.gshrms.common.core.page.TableSupport;
import com.gshrms.system.mapper.SysMenuMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.gshrms.common.annotation.DataScope;
import com.gshrms.common.core.domain.BaseEntity;
import com.gshrms.common.core.domain.entity.SysRole;
import com.gshrms.common.core.domain.entity.SysUser;
import com.gshrms.common.core.domain.model.LoginUser;
import com.gshrms.common.core.text.Convert;
import com.gshrms.common.utils.SecurityUtils;
import com.gshrms.common.utils.StringUtils;
import com.gshrms.framework.security.context.PermissionContextHolder;

/**
 * 数据过滤处理
 *
 * @author ruoyi
 */
@Aspect
@Component
public class DataScopeAspect {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 全部数据权限
     */
    public static final String DATA_SCOPE_ALL = "1";

    /**
     * 自定数据权限
     */
    public static final String DATA_SCOPE_CUSTOM = "2";

    /**
     * 部门数据权限
     */
    public static final String DATA_SCOPE_DEPT = "3";

    /**
     * 部门及以下数据权限
     */
    public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";

    /**
     * 仅本人数据权限
     */
    public static final String DATA_SCOPE_SELF = "5";

    /**
     * 数据权限过滤关键字
     */
    public static final String DATA_SCOPE = "dataScope";



    @Before("@annotation(controllerDataScope)")
    public void dataBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable {
        clearDataScope(point);
        handleDataQX(point, controllerDataScope);
    }


    protected void handleDataQX(final JoinPoint joinPoint, DataScope controllerDataScope) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();

        if (StringUtils.isNotNull(loginUser)) {
            SysUser currentUser = loginUser.getUser();
            // 如果是超级管理员，则不过滤数据
            //如果是主管理员,则不过滤数据
            if (StringUtils.isNotNull(currentUser) && currentUser.getUserType().equals("01")) {

            }
            //如果是子管理员,查询有权限的部门数据
            if (StringUtils.isNotNull(currentUser) && currentUser.getUserType().equals("02")) {
                LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SysMenu::getPerms,controllerDataScope.permission());
                SysMenu sysMenu = sysMenuMapper.selectOne(queryWrapper);

                if (controllerDataScope.permission().equals("org:farme:list")){
                    //如果是组织架构，走组织权限
                    orgQX(joinPoint, loginUser.getUserId(), sysMenu.getMenuId(),controllerDataScope.tableAlias());
                }else if (controllerDataScope.permission().equals("staff:flowTransfer:query")){
                    //如果是调动管理,走调动权限
                    transferQX(joinPoint, loginUser.getUserId(), sysMenu.getMenuId(),controllerDataScope.tableAlias());
                }else {
                    //如果不是,走数据权限
                    dataQX(joinPoint, loginUser.getUserId(), sysMenu.getMenuId(),controllerDataScope.tableAlias());
                }
            }
        }
    }

    /**
     * 调动权限
     * @param joinPoint
     * @param userId
     * @param menuId
     * @param tableAlias
     */

    public static void transferQX(JoinPoint joinPoint, Long userId,Long menuId,String tableAlias) {

        StringBuilder sqlString = new StringBuilder();
        // 多个自定数据权限使用in查询，避免多次拼接。
        // 动态拼接用户ID和菜单ID，防止硬编码
        sqlString.append(StringUtils.format(
                " {}.old_org_id IN ("+
                       "        SELECT a.org_id\n" +
                        "        FROM org_info a\n" +
                        "        WHERE a.del_flag = 0\n" +
                        "          AND EXISTS (SELECT 1\n" +
                        "                      FROM sys_user_menus sum\n" +
                        "            JOIN JSON_TABLE(\n" +
                        "            sum.authority_limit,\n" +
                        "            '$[*]' COLUMNS (val VARCHAR(10) PATH '$')) AS jt\n" +
                        "            WHERE sum.user_id = "+userId+"\n" +
                        "                AND sum.menu_id ="+menuId+"\n" +
                        "                AND (\n" +
                        "                      JSON_CONTAINS(a.ancestors_json, CAST(jt.val AS JSON))\n" +
                        "                          OR a.org_id = CAST(jt.val AS UNSIGNED)\n" +
                        "                      )\n" +
                        "            )"+

                ")",
                tableAlias
        ));
        if (StringUtils.isNotBlank(sqlString.toString())) {
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof CommonEntity) {
                CommonEntity commonEntity = (CommonEntity) params;
                commonEntity.setDataQXSql(sqlString.toString());
            }
        }
    }

    public static void dataQX(JoinPoint joinPoint, Long userId,Long menuId,String tableAlias) {

        StringBuilder sqlString = new StringBuilder();
        // 多个自定数据权限使用in查询，避免多次拼接。
        // 动态拼接用户ID和菜单ID，防止硬编码
        sqlString.append(StringUtils.format(
                " {}.org_id IN ("+
                        "        SELECT a.org_id\n" +
                        "        FROM org_info a\n" +
                        "        WHERE a.del_flag = 0\n" +
                        "          AND EXISTS (SELECT 1\n" +
                        "                      FROM sys_user_menus sum\n" +
                        "            JOIN JSON_TABLE(\n" +
                        "            sum.authority_limit,\n" +
                        "            '$[*]' COLUMNS (val VARCHAR(10) PATH '$')) AS jt\n" +
                        "            WHERE sum.user_id = "+userId+"\n" +
                        "                AND sum.menu_id ="+menuId+"\n" +
                        "                AND (\n" +
                        "                      JSON_CONTAINS(a.ancestors_json, CAST(jt.val AS JSON))\n" +
                        "                          OR a.org_id = CAST(jt.val AS UNSIGNED)\n" +
                        "                      )\n" +
                        "            )"+

                        ")",
                tableAlias
        ));
        if (StringUtils.isNotBlank(sqlString.toString())) {
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof CommonEntity) {
                CommonEntity commonEntity = (CommonEntity) params;
                commonEntity.setDataQXSql(sqlString.toString());
            }
        }
    }


    /**
     * 组织权限
     * @param joinPoint
     * @param userId
     * @param menuId
     * @param tableAlias
     */

    public static void orgQX(JoinPoint joinPoint, Long userId,Long menuId,String tableAlias) {
        StringBuilder sqlString = new StringBuilder();
        // 多个自定数据权限使用in查询，避免多次拼接。
        // 动态拼接用户ID和菜单ID，防止硬编码

        sqlString.append(StringUtils.format(" {}.org_id IN (" +
                        "SELECT DISTINCT CAST(TRIM(jt.val) AS UNSIGNED) AS id\n" +
                        "FROM (\n" +
                        "    SELECT \n" +
                        "        (\n" +
                        "            SELECT GROUP_CONCAT(DISTINCT id ORDER BY id)\n" +
                        "            FROM (\n" +
                        "                SELECT jt_org.org_id AS id\n" +
                        "                FROM JSON_TABLE(a.ancestors_json, '$[*]' COLUMNS (org_id INT PATH '$')) AS jt_org\n" +
                        "                UNION \n" +
                        "                SELECT a.org_id\n" +
                        "            ) AS combined_ids\n" +
                        "        ) AS merged_ids\n" +
                        "    FROM org_info_view a\n" +
                        "    JOIN (\n" +
                        "        SELECT DISTINCT CAST(jt.val AS UNSIGNED) AS merged_authority\n" +
                        "        FROM sys_user_menus sum\n" +
                        "        JOIN JSON_TABLE(\n" +
                        "            sum.authority_limit,\n" +
                        "            '$[*]' COLUMNS (val JSON PATH '$'\n" +
                        "        )) AS jt ON TRUE\n" +
                        "        WHERE sum.user_id =" + userId +"\n"+
                        "          AND sum.menu_id = "+ menuId +"\n" +
                        "    ) AS authorities \n" +
                        "        ON EXISTS (\n" +
                        "            SELECT 1\n" +
                        "            FROM JSON_TABLE(a.ancestors_json, '$[*]' COLUMNS (org_id INT PATH '$')) AS jt_org\n" +
                        "            WHERE jt_org.org_id = authorities.merged_authority\n" +
                        "        ) OR a.org_id = authorities.merged_authority\n" +
                        "    WHERE a.del_flag = 0\n" +
                        ") t\n" +
                        "JOIN JSON_TABLE(\n" +
                        "    CONCAT('[\"', REPLACE(t.merged_ids, ',', '\",\"'), '\"]'),\n" +
                        "    '$[*]' COLUMNS (val VARCHAR(255) PATH '$')\n" +
                        ") AS jt\n" +
                        "WHERE TRIM(jt.val) <> '' " +
                        ")"
                ,
                tableAlias
        ));

        if (StringUtils.isNotBlank(sqlString.toString())) {
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof CommonEntity) {
                CommonEntity commonEntity = (CommonEntity) params;
                commonEntity.setDataQXSql(sqlString.toString());
            }
        }
    }



    /**
     * 拼接权限sql前先清空params.dataScope参数防止注入
     */
    private void clearDataScope(final JoinPoint joinPoint) {
        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
            CommonEntity commonEntitym = (CommonEntity) params;
            commonEntitym.getParams().put("dataScope", "");
        }
    }


    @Before("@annotation(controllerDataScope)")
    public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable {
        clearDataScope(point);
        handleDataScope(point, controllerDataScope);
    }


    protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser)) {
            SysUser currentUser = loginUser.getUser();
            // 如果是超级管理员，则不过滤数据
                String permission = StringUtils.defaultIfEmpty(controllerDataScope.permission(), PermissionContextHolder.getContext());
                dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(),
                        controllerDataScope.userAlias(), permission);

        }
    }


    /**
     * 数据范围过滤
     *
     * @param joinPoint  切点
     * @param user       用户
     * @param deptAlias  部门别名
     * @param userAlias  用户别名
     * @param permission 权限字符
     */
    public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias, String permission) {
        StringBuilder sqlString = new StringBuilder();
        List<String> conditions = new ArrayList<String>();
        List<String> scopeCustomIds = new ArrayList<String>();

        // 角色都不包含传递过来的权限字符，这个时候sqlString也会为空，所以要限制一下,不查询任何数据
        if (StringUtils.isEmpty(conditions)) {
            sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias));
        }

        if (StringUtils.isNotBlank(sqlString.toString())) {
            Object params = joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) params;
                baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
            }
        }
    }



}
